<!--
源数据对象必须包含id及isChecked属性
-->
<template>
  <el-table
    ref="table"
    :data="data"
    :empty-text="emptyText"
    @select="handleSelect"
    @select-all="handleSelectAll"
    border
    stripe>
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column
      v-for="col of columns"
      :key="col.prop"
      :prop="col.prop"
      :label="col.label"
      :width="col.width">
    </el-table-column>
  </el-table>
</template>

<script>
  export default {
    name:"SimpleMultipleTable",
    props:{
      data: {
        type: Array,
        required: true
      },
      columns: {
        type: Array,
        required:true
      },
      emptyText: {
        type: String,
        default: "暂无数据"
      }
    },
    methods: {
      handleSelect(selection, row) {
        //另加一个isChecked属性，解决是否选中问题
        row.isChecked = !row.isChecked;
        this.$emit("select");
      },
      handleSelectAll(selection) {
        if(this.data.every(item=>item.isChecked)) {
          this.data.forEach(item=>item.isChecked = false);
        }else {
          this.data.forEach(item=>item.isChecked = true);
        }
        this.$emit("selectAll");
      },
      checkDefaultRows() {
        if(this.$refs["table"] !== undefined) {
          this.data.forEach(item => {
              if(item.isChecked) {
                this.$refs["table"].toggleRowSelection(item, true)
              }else {
                this.$refs["table"].toggleRowSelection(item, false)
              }
          });
        }
      },
      /**
       * 将isChecked为true的对象集合解析为数组
       * @param data 传输的数组，必须有id属性
       * @throws     非数组则抛出异常
       */
      getCheckedKeys(data) {
        if(!Array.isArray(data)) throw new Error("setCheckedKeys Expected Array, got Other");
        let idSet = new Set();
        data.forEach(item=>{
          if(item.isChecked) idSet.add(item.id);
        });
        return [...idSet];
      }
    },
    updated() {
      this.checkDefaultRows();
    }
  }
</script>



// WEBPACK FOOTER //
// SimpleMultipleTable.vue?0c1ee869